# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from urllib.parse import urlencode
from threading import Thread

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "太平康爱卫士老年恶性肿瘤疾病保险"

    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(45, 60)],
                # 性别
                "gender": ["M", "F"],
                # 保险金额
                "money": [str(i) + "0000" for i in range(2, 11)],
                # 保障期限
                "expire": ["10年", "20年"],
                # 交费间隔
                "interval": ["0", "3", "5", "10"],
                # 交费类型
                "payType": ["年交", "月交"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(61, 70)],
                # 性别
                "gender": ["M", "F"],
                # 保险金额
                "money": [str(i) + "0000" for i in range(2, 11)],
                # 保障期限
                "expire": ["10年"],
                # 交费间隔
                "interval": ["0", "3", "5", "10"],
                # 交费类型
                "payType": ["年交", "月交"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(71, 76)],
                # 性别
                "gender": ["M", "F"],
                # 保险金额
                "money": [str(i) + "0000" for i in range(2, 11)],
                # 保障期限
                "expire": ["10年"],
                # 交费间隔
                "interval": ["0", "3", "5"],
                # 交费类型
                "payType": ["年交", "月交"]
            }
        }

        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["expire"],
                             plan[k]["interval"], plan[k]["payType"]):
                data = Helper.formatProductInfo(plan[k], v)
                if data["interval"] == "0":
                    data["payType"] = "趸交"
                else:
                    pass
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    def requestJson(self, dt=None, mysql=None):

        params = '''
        pageName: productAdd
        goods_id: 61860
        merchant_id: B2C
        toubaoli_money: 
        productCode: 50000730
        productId: 397ed51c-038b-4f5a-9444-bbe9b4473bca
        riskCode: 0110000195
        productName: 康爱卫士老年恶性肿瘤疾病保险
        insuredPrice: 13016
        insured.birthday: 
        templateType: 1
        employee_id: 
        channel: 
        empNo: 
        newsCode: 
        twoMonthInsuredPrice: 
        loginUserId: 
        insured.age: 45
        insured.sex: 1
        policy.amount: 10
        policy.dateRemark: 10
        policy.chargeType: 4
        policy.chargeYear: 03
        person.mobilenum: 承保短信将发送至您的手机
        policy.showMessage: true
        '''
        if dt["payType"] == "年交":
            chargeType = "1"

        elif dt["payType"] == "月交":
            chargeType = "4"
        else:
            chargeType = "5"
        chargeYear = "0" + dt["interval"] if (int(dt["interval"]) < 10 and int(dt["interval"]) != 0) else dt["interval"]
        code = "50000730" if dt["expire"] == "10年" else "50000731"
        data = Helper.perfectJson(params)
        data["insured.age"] = dt["year"]
        data["insured.sex"] = "1" if dt["gender"] == "M" else "2"
        data["policy.amount"] = "0" +  str(int(int(dt["money"]) / 10000)) if  (int(int(dt["money"]) / 10000)) <10 else str(int(int(dt["money"]) / 10000))
        data["policy.dateRemark"] = dt["expire"].replace("年","")
        data["policy.chargeType"] = chargeType
        data["policy.chargeYear"] = chargeYear
        data["productCode"] = code
        payload = urlencode(data).replace("+", "")
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "totalPremium" in r.text:
            print( r.text )
            price = Helper.decimalParse(r.json()["totalPremium"])
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("\n/*产品价格更新失败:%d*/"%dt["id"])

    def startProcess(self):

        threads = []
        for i in range(3):
            mysql = MysqlClient()
            t = Thread(target=Helper.runProcess,args=(mysql,self.name,self.requestJson,))
            t.start()
            threads.append( t )
        for t in threads:
            t.join()
